<script lang="ts" setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dalyJysqDialog from '../dialogs/daly-jysq-dialog.vue'
import TreeUtilDTO from '@/utils/tree'
import jyglService from '@/api/jygl'

// 入参
const props = defineProps({
  jylxData: {
    type: Object,
  },
})

const activeName = ref('ssda')
const isLoading = ref(false)
const jysqDialogRef = ref()

// 生命周期

// tabs切换
// const changeTabs = (val: string) => {
//   //
//   switch (val) {
//     case 'ssda':
//       queryJycajsj()
//       break
//     case 'spda':
//       queryJycspsjlb()
//       break
//     default:
//       break
//   }
// }

/*
 * 移除目录
 */
const ycml = () => {
  ElMessageBox.confirm('确定移除选中数据？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    let moveList: any = []
    if (ssMultipleSelection.value.length > 0) {
      Promise.all(
        ssMultipleSelection.value.map((item: any) => {
          moveList.push(item.jycbh)
          return jyglService.queryJycajwsmlsj({ ajbh: item.ajbh })
        }),
      )
        .then((res) => {
          if (res.length > 0) {
            res.forEach((el) => {
              el.data.forEach((item) => {
                moveList.push(item.jycbh)
              })
            })
            yichu(moveList)
          }
        })
        .catch((err) => {
          !err.isError && ElMessage({ type: 'warning', message: err.message })
        })
    } else {
      dialogTableData.value.forEach((item) => {
        const rowDeleteList = TreeUtilDTO.flatten(item.treeData).filter((el) => el.cj !== '1')
        rowDeleteList.forEach((el) => {
          moveList.push(el.jycbh)
        })
      })
      yichu(moveList)
    }

    if (spMultipleSelection.value.length > 0) {
      spMultipleSelection.value.forEach((item: any) => {
        moveList.push(item.jycbh)
      })

      yichu(moveList)
    }

    // if (dialogTableData.value.length > 0) {
    //   dialogTableData.value.forEach((item: any) => {
    //     let treeArr = TreeUtilDTO.flatten(item.treeData).map((item) => item.jycbh)
    //     moveList.push(...treeArr)
    //   })
    // }
    // if () {

    // }
  })
}

const yichu = (moveList?: any) => {
  const params = {
    jycbhList: moveList,
  }
  jyglService
    .delJycjl(params)
    .then(() => {
      if (activeName.value === 'ssda') {
        queryJycajsj()
        queryJycspsjlb()
        ElMessage.success('移除成功')
        // queryJycajwsmlsj(expandedRowData.value)
        expandRowKeys.value = []
        ssMultipleSelection.value = []
        spMultipleSelection.value = []
        dialogTableData.value = []
        rowListData.value = []
        return
      }
      queryJycajsj()
      queryJycspsjlb()
      ElMessage.success('移除成功')
      ssMultipleSelection.value = []
      spMultipleSelection.value = []
      dialogTableData.value = []
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/*
 * 提交申请（打开借阅申请）
 */

const tjsqList = ref<any[]>([])
const tjsq = () => {
  if (
    !ssMultipleSelection.value.length &&
    !dialogTableData.value.length &&
    !spMultipleSelection.value.length
  ) {
    ElMessage.warning('请选择档案')
    return
  }
  const ssMultSave = ssMultipleSelection.value.some((el) =>
    ssMultipleSelection.value.find((item) => el.cbdwbm !== item.cbdwbm),
  )

  const spMultSave = spMultipleSelection.value.some((el) =>
    spMultipleSelection.value.find((item) => el.dwbm !== item.dwbm),
  )

  if (ssMultSave || spMultSave) {
    ElMessage.warning('只允许借阅同一个院的档案数据')
    return
  }
  tjsqList.value = []
  ssMultipleSelection.value?.forEach((item: any) => {
    const tjshFind = dialogTableData.value.find((el) => item.jycbh === el.jycbh)
    if (tjshFind) {
      tjsqList.value.push(tjshFind)
    } else {
      const params = {
        ajbh: item.ajbh,
      }
      jyglService
        .queryJycajwsmlsj(params)
        .then((res) => {
          tjsqList.value.push({
            ...item,
            treeData: TreeUtilDTO.getTreeData(res.data, 'bh', 'fbh'),
          })
          jysqDialogRef.value.openDialog(
            'add',
            '视频档案诉讼',
            tjsqList.value,
            spMultipleSelection.value,
          )
        })
        .catch((err) => {
          !err.isError && ElMessage({ type: 'warning', message: err.message })
        })
    }
  })
  jysqDialogRef.value.openDialog(
    'add',
    '视频档案诉讼',
    dialogTableData.value,
    spMultipleSelection.value,
  )
  closeDialog()
}

/*
 * 打开弹窗
 */
//
const dialogVisible = ref(false)
const jylxDataObj = ref()
const openDialog = () => {
  queryJycajsj()
  queryJycspsjlb()
  jylxDataObj.value = props.jylxData
  dialogVisible.value = true
}

const ssTableData = ref<any[]>([])
const spTableData = ref<any[]>([])
/*
 * 查询借阅车诉讼档案
 */
const queryJycajsj = () => {
  isLoading.value = true
  jyglService
    .queryJycajsj()
    .then((res: any) => {
      ssTableData.value = res.data
      if (!ssTableData.value || !ssTableData.value.length) {
        activeName.value = 'spda'
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      isLoading.value = false
    })
}

const ssMultipleSelection = ref<any[]>([])
const ssHandleSelectionChange = (val: any[]) => {
  ssMultipleSelection.value = val
}
const spMultipleSelection = ref<any[]>([])
const spHandleSelectionChange = (row: any) => {
  spMultipleSelection.value = row
}

const dalyTreeRef = ref<any>([])

/*
 * 查询借阅车诉讼目录
 */

const queryJycajwsmlsj = (expandedRows: any) => {
  if (expandedRows.treeData) {
    // const diaData = dialogTableData.value.find((el) => el.jycbh === expandedRows.jycbh)
    const ssList = ssMultipleSelection.value.find((el) => el.jycbh === expandedRows.jycbh)
    if (ssList) {
      const diaSsData = dialogTableData.value.find((el) => el.jycbh === ssList.jycbh)

      // if (diaSsData) {
      //   return
      // }

      dialogTableData.value.push({
        ...expandedRows,
        treeData: TreeUtilDTO.getTreeData(expandedRows.treeData, 'bh', 'fbh'),
      })

      nextTick(() => {
        dialogTableData.value.forEach((item: any, index: number) => {
          if (item.treeData) {
            const checkedList = TreeUtilDTO.flatten(item.treeData).map((item: any) => item.jycbh)
            const ssIndex = ssTableData.value.findIndex(
              (el: any) => el.jycbh === expandedRows.jycbh,
            )
            dalyTreeRef.value[ssIndex]?.setCheckedKeys(checkedList)
          }
        })
        // const ssIndex = ssTableData.value.findIndex(
        //   (item: any) => item.jycbh === expandedRows.jycbh,
        // )
        // dalyTreeRef.value[ssIndex]?.setCheckedKeys(checkedList)
      })
    }
    return
  }
  const params = {
    ajbh: expandedRows.ajbh,
  }
  jyglService
    .queryJycajwsmlsj(params)
    .then((res) => {
      expandedRows.treeData = TreeUtilDTO.getTreeData(res.data, 'bh', 'fbh')

      const ssList = ssMultipleSelection.value.find((el) => el.jycbh === expandedRows.jycbh)
      if (ssList) {
        const diaSsData = dialogTableData.value.find((el) => el.jycbh === ssList.jycbh)
        if (diaSsData) {
          return
        }

        dialogTableData.value.push({
          ...expandedRows,
          // treeData: TreeUtilDTO.getTreeData(res.data, 'bh', 'fbh'),
          treeData: res.data,
        })
        nextTick(() => {
          dialogTableData.value.forEach((item: any, index: number) => {
            if (item.treeData) {
              const checkedList = TreeUtilDTO.flatten(item.treeData).map((item: any) => item.jycbh)
              const ssIndex = ssTableData.value.findIndex(
                (el: any) => el.jycbh === expandedRows.jycbh,
              )
              dalyTreeRef.value[ssIndex]?.setCheckedKeys(checkedList)
            }
          })
        })
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/*
 * 查询借阅车视频档案
 */
const queryJycspsjlb = () => {
  const params = {}
  jyglService
    .queryJycspsjlb()
    .then((res) => {
      spTableData.value = res.data
      if (!spTableData.value || !spTableData.value.length) {
        activeName.value = 'ssda'
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

const expandRowKeys = ref<any>([])
const expandedRowData = ref<any>({})
const rowListData = ref<any[]>([])
const expandChange = (expandedRows: { ajbh: string; jycbh: string }, rowList: any) => {
  expandedRowData.value = expandedRows
  rowListData.value = rowList
  if (rowList.length) {
    expandRowKeys.value = rowList.map((item: any) => item.jycbh)
  } else {
    expandRowKeys.value = []
  }
  queryJycajwsmlsj(expandedRows)
}

const ssMultipleTableRef = ref()
//  选择复选框
const dialogTableData = ref<any[]>([])
const checkTree = (checks: any, row: any) => {
  dialogTableData.value = dialogTableData.value.filter((el: any) => {
    return el.jycbh !== row.jycbh
  })
  if (checks.checkedNodes.length > 0) {
    dialogTableData.value.push({
      ...row,
      treeData: TreeUtilDTO.getTreeData(
        [
          ...checks.checkedNodes.map((el: any) => {
            return { ...el, children: [] }
          }),
          ...checks.halfCheckedNodes.map((el: any) => {
            return { ...el, children: [] }
          }),
        ],
        'bh',
        'fbh',
      ),
    })
  }

  if (dialogTableData.value.length) {
    dialogTableData.value.forEach((item: any) => {
      const rowObjData = TreeUtilDTO.flatten(
        rowListData.value?.find((el) => el.jycbh === item.jycbh)?.treeData,
      ).map((el) => {
        return {
          ...el,
          children: [],
        }
      })
      if (
        TreeUtilDTO.flatten(item.treeData).length &&
        TreeUtilDTO.flatten(item.treeData).length === rowObjData.length
      ) {
        ssMultipleTableRef.value.toggleRowSelection(row, true)
      } else {
        ssMultipleTableRef.value.toggleRowSelection(row, false)
      }
    })
    const diaFind = dialogTableData.value.find((item) => item.jycbh === row.jycbh)
    if (!diaFind) {
      ssMultipleTableRef.value.toggleRowSelection(row, false)
    }
  } else {
    ssMultipleTableRef.value.toggleRowSelection(row, false)
  }
}

const getRefs = (el: any, index: number) => {
  dalyTreeRef.value[index] = el
}

/*
 * 关闭弹框
 */
const closeDialog = () => {
  expandRowKeys.value = []
  rowListData.value = []
  activeName.value = 'ssda'
  dialogTableData.value = []
  dalyTreeRef.value = []
  dialogVisible.value = false
}
// select事件
const selectSsda = (selection: any, row: any) => {
  if (selection.includes(row) && row.treeData?.length) {
    const diaSsData = dialogTableData.value.find((el) => el.jycbh === row.jycbh)
    if (diaSsData) {
      const selectRow = selection.find((val) => val.jycbh === row.jycbh)
      const ssIndex = ssTableData.value.findIndex((el: any) => el.jycbh === row.jycbh)
      const checkedList = TreeUtilDTO.flatten(selectRow.treeData).map((item: any) => item.jycbh)
      dalyTreeRef.value[ssIndex]?.setCheckedKeys(checkedList)
      return
    }
    dialogTableData.value.push({
      ...row,
      treeData: row.treeData,
    })
    nextTick(() => {
      dialogTableData.value.forEach((item: any, index: number) => {
        if (item.treeData) {
          const checkedList = TreeUtilDTO.flatten(item.treeData).map((item: any) => item.jycbh)
          const ssIndex = ssTableData.value.findIndex((el: any) => el.jycbh === row.jycbh)
          dalyTreeRef.value[ssIndex]?.setCheckedKeys(checkedList)
        }
      })
    })
  } else if (!selection.includes(row) && row.treeData?.length) {
    const diaSsData = dialogTableData.value.find((el) => el.jycbh === row.jycbh)
    if (diaSsData) {
      const ssIndex = dialogTableData.value.findIndex((el: any) => el.jycbh === row.jycbh)
      dialogTableData.value.splice(ssIndex, 1)
      nextTick(() => {
        const ssIndex = ssTableData.value.findIndex((el: any) => el.jycbh === row.jycbh)
        dalyTreeRef.value[ssIndex]?.setCheckedKeys([])
      })
    }
  }
}

// 全选事件
const selectAllSsda = (selection: any[]) => {
  console.log(selection)
  if (selection.length) {
    nextTick(() => {
      ssTableData.value.forEach((da, i) => {
        if (da.treeData)
          dalyTreeRef.value[i]?.setCheckedKeys(da.treeData.map((row: any) => row.jycbh))
      })
    })
  } else {
    nextTick(() => {
      ssTableData.value.forEach((_, i) => {
        dalyTreeRef.value[i]?.setCheckedKeys([])
      })
    })
  }
}

// watch(
//   () => rowListData,
//   () => {
//     console.log(ssTableData.value, 'ssTableData')
//     console.log(dialogTableData.value, 'dialogTableData')

//     if (rowListData.value.length > 0) {
//       rowListData.value.forEach((el) => {
//         const toggleRow = dialogTableData.value.find((item) => item.jycbh === el.jycbh)
//         if (toggleRow) {

//         }
//       })
//     }
//   },
//   {
//     deep: true,
//   },
// )

// watch(
//   () => dialogTableData,
//   () => {
//     console.log(dialogTableData.value);

//   },
//   {
//     deep: true,
//   },
// )

defineExpose({ openDialog })
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    title="借阅车"
    width="80%"
    :close-on-click-modal="false"
    :before-close="closeDialog"
  >
    <div class="dialog-box">
      <div class="delete-button">
        <el-button
          type="primary"
          @click="ycml"
          :disabled="
            !dialogTableData.length && !ssMultipleSelection.length && !spMultipleSelection.length
          "
          >移除</el-button
        >
      </div>
      <div class="content-tabs">
        <el-tabs class="td-tabs" v-model="activeName">
          <el-tab-pane
            v-if="ssTableData.length"
            label="&nbsp;&nbsp;&nbsp;&nbsp;诉讼档案&nbsp;&nbsp;&nbsp;&nbsp;"
            name="ssda"
            lazy
          >
            <el-table
              ref="ssMultipleTableRef"
              :data="ssTableData"
              highlight-current-row
              row-key="jycbh"
              height="calc(70vh - 80px)"
              @selection-change="ssHandleSelectionChange"
              @expand-change="expandChange"
              @select="selectSsda"
              @select-all="selectAllSsda"
              :expand-row-keys="expandRowKeys"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column type="expand">
                <template #default="props">
                  <el-tree
                    style="margin-left: 90px"
                    :ref="(el:any) => getRefs(el, props.$index)"
                    :data="props.row.treeData"
                    :check-strictly="false"
                    :props="{ label: 'mc', children: 'children' }"
                    node-key="jycbh"
                    show-checkbox
                    default-expand-all
                    highlight-current
                    @check="(_:any, checks: any)=>checkTree(checks, props.row)"
                  >
                    <template #default="{ data }">
                      <span class="custom-tree-node">
                        <span>{{ data.mc }} ({{ data.wjsl }})</span>
                      </span>
                    </template>
                  </el-tree>
                </template>
              </el-table-column>
              <el-table-column prop="ajdh" label="档号" width="200" />
              <el-table-column prop="ajmc" label="案件名称" show-overflow-tooltip />
              <el-table-column prop="bmsah" label="部门受案号" show-overflow-tooltip />
              <el-table-column prop="dsrmc" label="当事人" />
              <el-table-column prop="aymc" label="案由" />
              <el-table-column prop="cbjcg" label="检察官" />
              <el-table-column prop="cbdwmc" label="档案所属院" />
            </el-table>
          </el-tab-pane>
          <el-tab-pane
            v-if="spTableData.length"
            label="&nbsp;&nbsp;&nbsp;&nbsp;视频档案&nbsp;&nbsp;&nbsp;&nbsp;"
            name="spda"
            lazy
          >
            <!-- :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" -->
            <el-table
              ref="spMultipleTableRef"
              :data="spTableData"
              highlight-current-row
              row-key="jycbh"
              height="calc(70vh - 80px)"
              @selection-change="spHandleSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="dh" label="档号" width="200" />
              <el-table-column prop="tm" label="题名" />
              <el-table-column prop="splx" label="视频类型" />
              <el-table-column prop="lzz" label="录制者" />
              <el-table-column prop="lzrq" label="录制日期" />
              <el-table-column prop="ljdw" label="档案所属院" />
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="tjsq()" :loading="isLoading">提交</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 新增借阅申请 -->
  <!-- <jyc-jysq-dialog ref="jycJysqDialogRefs" /> -->
  <daly-jysq-dialog ref="jysqDialogRef" />
</template>
<style lang="scss" scoped>
.dialog-box {
  width: 100%;
  max-height: 70vh;
  display: flex;
  flex-direction: column;
  .delete-button {
    padding-bottom: 10px;
  }
  .content-tabs {
    max-height: 100%;
    // overflow: auto;
  }
}

.td-tabs {
  max-height: 100%;
  min-height: 70vh;
  border: 0;
  :deep(.el-tabs__content) {
    max-height: 100%;
    padding: 10px 0;
  }
  :deep(.el-tabs__item) {
    // height: 36px;
    padding: 0;
    &:hover,
    &.is-active {
      background-color: transparent;
    }
  }
}

:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  border-right: none !important;
  color: #0090ff;
  background-color: #d9edff;
}
</style>
